<?php
/**
 * User API
 * 
 * @author ShuangYa
 * @package EasyAccount
 * @category Controller
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/easyaccount/license
 */
namespace ea\library\APIHandler;

use ea\model\User as UserModel;
use ea\model\Token;
use ea\model\UserGroup;
use ea\model\OAuthClient;
use ea\library\Utils;

class User {
	//获取用户信息
	public static function get($id) {
		$u = UserModel::get($id);
		unset($u['password']);
		return ['user' => $u];
	}
	//验证用户名与密码是否正确
	public static function verify($type, $user, $password) {
		if ($type !== 'mail' && $type !== 'phone' && $type !== 'id') {
			return '类型无效';
		}
		$result = UserModel::verify($type, $user, $password);
		if ($result === FALSE) {
			return [
				'valid' => FALSE,
				'user' => NULL
			];
		} else {
			unset($result['password']);
			return [
				'valid' => TRUE,
				'user' => $result
			];
		}
	}
	//设置用户状态
	public static function status($id, $status) {
		//创始人账户不可操作
		$user = UserModel::get($id);
		$rs = TRUE;
		if ($user['status'] != $status) {
			$rs = UserModel::set(['status' => $status], $id);
		}
		//失效所有token
		Token::delUser($id);
		if ($rs === FALSE) {
			return '操作失败';
		} else {
			return [];
		}
	}
	//保存用户
	public static function save($data) {
		$id = intval($data['id']);
		$update = [];
		if (isset($data['role'])) {
			$role = intval($data['role']);
			if ($role !== 0) {
				if ($role !== 1 && $role !== 2) {
					return '用户类型无效';
				}
				$update['role'] = $role;
			}
		}
		foreach (['nickname', 'realname', 'phone', 'mail', 'avatar', 'group_id'] as $v) {
			if (isset($data[$v]) && !empty($data[$v])) {
				$update[$v] = $data[$v] === '__EMPTY__' ? '' : $data[$v];
			}
		}
		//如果是新增，则传递密码
		if ($id === -1) {
			$update['password'] = empty($data['password']) ? Utils::randStr(8) : $data['password'];
			$id = UserModel::add($update);
		} else {
			if (!empty($data['password'])) {
				$update['password'] = $data['password'];
				//失效所有token
				Token::delUser($id);
			}
			UserModel::set($update, $id);
		}
		return [
			'id' => $id,
			'password' => $update['password'] ?? ""
		];
	}
	//删除用户
	public static function del($id) {
		//创始人账户不可操作
		$user = UserModel::get($id);
		$rs = UserModel::del($id);
		Token::delUser($id);
		if ($rs === FALSE) {
			return '操作失败';
		}
		return [];
	}
}